import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getUserId, setUserId, removeUserId } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    userId: getUserId(),
    zcrouter: [], //  菜单
    zcbtn: {}, // 按钮
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_USER_ID: (state, userId) => {
        state.userId = userId
    },
    SET_ZCROUTER: (state, zcrouter) => {
        state.zcrouter = zcrouter
    },
    SET_ZCBTN: (state, zcbtn) => {
        state.zcbtn = zcbtn
    }
}

const actions = {
    // 登录
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password }).then(data => {
                // 登录返回的数据 
                commit('SET_TOKEN', data.key)
                commit('SET_USER_ID', data.id)
                setToken(data.key)
                setUserId(data.id)

                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 获取用户详情
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            // console.log('获取兴趣', state.userId)
            getInfo(state.token, state.userId).then(data => {

                // console.log(state.userId)
                if (!data) {
                    reject('Verification failed, please Login again.')
                }
                const roles = ["admin"]
                    // 路由 姓名  头像
                const { username, avatar, role_data } = data

                let arrx = {}; // 按钮权限

                // 权限清洗函数
                function zc(item) {
                    if (item.length !== 0) {
                        item.forEach((e, i) => {
                            if (e.type == 3) {

                                arrx[e.sign] = e.hidden == 0 ? true : false
                                if (item.length - 1 == i) {
                                    item = item.length = 0;
                                }
                            } else {
                                zc(e.children);
                            }
                        });
                    }
                }

                function zc2(item) {
                    if (item.length !== 0) {
                        item.forEach((e, i) => {
                            if (e.type == 3) {
                                item = item.length = 0;
                            } else {
                                zc2(e.children);
                            }
                        });
                    }
                }

                //菜单权限
                let obj = JSON.parse(JSON.stringify(role_data));
                let obj2 = JSON.parse(JSON.stringify(role_data));
                zc(obj);
                commit('SET_ZCBTN', arrx)
                    // console.log('按钮权限', arrx)
                zc2(obj2)
                commit('SET_ZCROUTER', obj2)


                commit('SET_ROLES', roles)
                commit('SET_NAME', username)
                commit('SET_AVATAR', avatar)

                resolve({ roles })

            }).catch(error => {
                reject(error)
            })
        })
    },

    // // user logout
    // logout({ commit, state, dispatch }) {
    //     return new Promise((resolve, reject) => {
    //         logout(state.token).then(() => {
    //             commit('SET_TOKEN', '')
    //             commit('SET_ROLES', [])

    //             removeToken()
    //             resetRouter()

    //             // reset visited views and cached views
    //             // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
    //             dispatch('tagsView/delAllViews', null, { root: true })

    //             resolve()
    //         }).catch(error => {
    //             reject(error)
    //         })
    //     })
    // },

    // 退出登录
    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {

            commit('SET_NAME', '')
            commit('SET_ZCROUTER', {})
            commit('SET_TOKEN', '')
            commit('SET_USER_ID', '')
            commit('SET_ROLES', [])
            commit('SET_AVATAR', '')
            removeToken()
            removeUserId()
            resetRouter()

            // reset visited views and cached views
            // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
            dispatch('tagsView/delAllViews', null, { root: true })

            resolve()

        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
        })
    },

    // dynamically modify permissions
    async changeRoles({ commit, dispatch }, role) {
        const token = role + '-token'

        commit('SET_TOKEN', token)
        setToken(token)

        const { roles } = await dispatch('getInfo')

        resetRouter()

        // generate accessible routes map based on roles
        const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
            // dynamically add accessible routes
        router.addRoutes(accessRoutes)

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}